<script setup lang="tsx">
import type { DataTableColumns, FormInst } from 'naive-ui'
import { useBoolean } from '@/hooks'
import { deleteCollector, fetchCollectorList } from '@/service'
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui'
import CollectorModal from './components/CollectorModal.vue'

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const { bool: visible, setTrue: openModal, setFalse: closeModal } = useBoolean(false)

const initialModel = {
  name: '',
  type: '',
}
const model = ref({ ...initialModel })

const formRef = ref<FormInst | null>()

// 删除采集器
async function handleDelete(name: string) {
  try {
    startLoading()
    const { isSuccess, message } = await deleteCollector(name)
    if (isSuccess) {
      window.$message.success('删除成功')
      await getCollectorList()
    }
    else {
      window.$message.error(message || '删除失败')
    }
  }
  catch (e: any) {
    window.$message.error(e.message || '删除失败')
  }
  finally {
    endLoading()
  }
}

// 获取类型标签颜色
function getTypeTagColor(type: string) {
  const colorMap: Record<string, any> = {
    Serial: 'success',
    TcpClient: 'info',
    TcpServer: 'warning',
    Mqtt: 'error',
  }
  return colorMap[type] || 'default'
}

// 表格列定义
const columns: DataTableColumns<Api.Collector.Info> = [
  {
    title: '采集器名称',
    align: 'center',
    key: 'name',
    width: 150,
  },
  {
    title: '类型',
    align: 'center',
    key: 'type',
    width: 120,
    render: (row) => {
      return (
        <NTag type={getTypeTagColor(row.type)}>
          {row.type}
        </NTag>
      )
    },
  },
  {
    title: '地址',
    align: 'center',
    key: 'address',
    width: 150,
    render: (row) => {
      return row.address || '-'
    },
  },
  {
    title: '超时(ms)',
    align: 'center',
    key: 'timeout',
    width: 100,
    render: (row) => {
      return row.timeout || '-'
    },
  },
  {
    title: '间隔(ms)',
    align: 'center',
    key: 'interval',
    width: 100,
    render: (row) => {
      return row.interval || '-'
    },
  },
  {
    title: '状态',
    align: 'center',
    key: 'enable',
    width: 100,
    render: (row) => {
      return (
        <NTag type={row.enable ? 'success' : 'default'}>
          {row.enable ? '启用' : '禁用'}
        </NTag>
      )
    },
  },
  {
    title: '更新时间',
    align: 'center',
    key: 'updatedAt',
    width: 180,
    render: (row) => {
      return row.updatedAt ? new Date(row.updatedAt * 1000).toLocaleString() : '-'
    },
  },
  {
    title: '操作',
    align: 'center',
    key: 'actions',
    width: 180,
    fixed: 'right',
    render: (row) => {
      return (
        <NSpace justify="center">
          <NButton
            size="small"
            onClick={() => handleEditTable(row)}
          >
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.name)}>
            {{
              default: () => '确认删除该采集器吗？',
              trigger: () => <NButton size="small" type="error">删除</NButton>,
            }}
          </NPopconfirm>
        </NSpace>
      )
    },
  },
]

const listData = ref<Api.Collector.Info[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 20,
  pageCount: 0,
  itemCount: 0,
})

onMounted(() => {
  getCollectorList()
})

async function getCollectorList() {
  try {
    startLoading()
    const { isSuccess, data } = await fetchCollectorList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...model.value, // 传递搜索条件
    })
    if (isSuccess && data) {
      listData.value = data.lists || []
      pagination.itemCount = data.count || 0
      pagination.pageCount = Math.ceil(pagination.itemCount / pagination.pageSize)
    }
  }
  catch (e: any) {
    window.$message.error(e.message || '获取采集器列表失败')
  }
  finally {
    endLoading()
  }
}

function handlePageChange(page: number) {
  pagination.page = page
  getCollectorList()
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize
  pagination.page = 1
  getCollectorList()
}

function handleResetSearch() {
  model.value = { ...initialModel }
  pagination.page = 1
  getCollectorList()
}

function handleSearch() {
  pagination.page = 1
  getCollectorList()
}

type ModalType = 'add' | 'edit'
const modalType = ref<ModalType>('add')
function setModalType(type: ModalType) {
  modalType.value = type
}

const editData = ref<Api.Collector.Info | null>(null)
function setEditData(data: Api.Collector.Info | null) {
  editData.value = data
}

function handleEditTable(row: Api.Collector.Info) {
  setEditData(row)
  setModalType('edit')
  openModal()
}

function handleAddTable() {
  setEditData(null)
  setModalType('add')
  openModal()
}

async function handleModalSuccess() {
  closeModal()
  await getCollectorList()
}
</script>

<template>
  <NSpace vertical size="large">
    <n-card title="采集器列表">
      <template #header-extra>
        <NButton type="primary" @click="handleAddTable">
          <template #icon>
            <NovaIcon icon="icon-park-outline:add-one" />
          </template>
          新建采集器
        </NButton>
      </template>

      <!-- 搜索表单 -->
      <n-form ref="formRef" :model="model" label-placement="left" inline :show-feedback="false" class="mb-4">
        <n-flex>
          <n-form-item label="采集器名称" path="name">
            <n-input v-model:value="model.name" placeholder="请输入采集器名称" />
          </n-form-item>
          <n-form-item label="类型" path="type">
            <n-input v-model:value="model.type" placeholder="请输入类型" />
          </n-form-item>
          <n-flex class="ml-auto">
            <NButton type="primary" @click="handleSearch">
              <template #icon>
                <NovaIcon icon="icon-park-outline:search" />
              </template>
              搜索
            </NButton>
            <NButton strong secondary @click="handleResetSearch">
              <template #icon>
                <NovaIcon icon="icon-park-outline:redo" />
              </template>
              重置
            </NButton>
          </n-flex>
        </n-flex>
      </n-form>

      <!-- 数据表格 -->
      <n-data-table
        :columns="columns"
        :data="listData"
        :loading="loading"
        :scroll-x="1200"
      />

      <!-- 分页器 -->
      <div class="mt-4 flex justify-end">
        <n-pagination
          v-model:page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-count="pagination.pageCount"
          :item-count="pagination.itemCount"
          show-size-picker
          :page-sizes="[10, 20, 30, 50, 100]"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </div>
    </n-card>

    <!-- 采集器编辑/新增弹窗 -->
    <CollectorModal
      v-model:visible="visible"
      :type="modalType"
      :modal-data="editData"
      @success="handleModalSuccess"
    />
  </NSpace>
</template>

